<template>
  <a-row :gutter="10">
    <a-col :sm="24" style="margin-bottom: 20px">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="7" :sm="8">
                <a-form-item
                  label="订单编号"
                  :labelCol="{ span: 5 }"
                  :wrapperCol="{ span: 18 }"
                >
                  <a-input
                    placeholder="请输入订单编号"
                    v-model="threadForm.leadsCode"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="7" :sm="8">
                <a-form-item
                  label="售后跟进人"
                  :labelCol="{ span: 5 }"
                  :wrapperCol="{ span: 18 }"
                >
                  <a-input
                    placeholder="请输入售后跟进人"
                    v-model="threadForm.aftersaleUserName"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="7" :sm="8">
                <a-form-item
                  label="线索状态"
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 18 }"
                >
                  <a-select
                    v-model="threadForm.aftersaleStatus"
                    placeholder="请选择线索状态"
                    @change="onStatusChange"
                  >
                    <a-select-option
                      v-for="item in statusOptions"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :md="9" :sm="8">
                <a-form-item
                  :labelCol="{ span: 4 }"
                  :wrapperCol="{ span: 18, offset: 5 }"
                >
                  <!-- <a-button type="primary" @click="threadAdd">新增</a-button> -->
                  <a-button type="primary" @click="selectInfo">查询</a-button>
                  <a-button type="primary" style="margin-left: 8px" @click="resetForm"
                    >重置</a-button
                  >
                  <a-button type="primary" style="margin-left: 8px" v-has="'afster:export'" @click="Export">导出</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div style="margin-top: 15px">
          <a-table
            style="height: 500px"
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            @change="handleTableChange"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
          >
            <span slot="action" slot-scope="next, record">
              <a @click="showDrawer(record)">详情</a>
              <a-divider type="vertical" />
              <a @click="openAllotDialog(record)">分配</a>
            </span>
          </a-table>
        </div>
      </a-card>
    </a-col>
    <!-- 分配弹框 -->
    <a-modal
      title="分配"
      destroyOnClose
      :visible="visibleCreateModal"
      okText="确认分配"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :zIndex="zIndex"
    >
      <div class="allotDialog-top">
        <div class="allotDialog-info">
          <div class="info-left">
            <div class="phone">
              <span>{{ contacts }}</span> <span>{{ contactTel }}</span>
            </div>
            <div class="info-tag">
              {{
                aftersaleStatus == 1 ? "待分配" : aftersaleStatus == 2 ? "跟进中" : "完成"
              }}
            </div>
          </div>
        </div>
        <div class="allotDialog-remark">
          <span>备注：</span> <span>{{ remarks }}</span>
        </div>
      </div>
      <div class="select-content">
        <div class="select-title">
          <div>选择要分给的对象（只可分配给您的直属下属）</div>
        </div>
        <div class="select-btn">
          <div>
            <a-cascader
              :options="options"
              :field-names="{ label: 'departName', value: 'key', children: 'children' }"
              placeholder="请选择要分给的部门"
              @change="typeChange"
            />
          </div>
          <div>
            <a-select v-model="ownerUserId" style="width: 200px">
              <a-select-option v-for="item in roleList" :key="item.id">
                {{ item.username }}
              </a-select-option>
            </a-select>
          </div>
        </div>
      </div>
    </a-modal>
    <!-- 备注 -->
    <a-modal
      title="订单跟进"
      :visible="remarkShow"
      @ok="handleRemark"
      @cancel="remarkCancel"
    >
      <div class="remarksDis">
        <a-textarea
          v-model="saleRemarks"
          placeholder="请输入备注"
          :auto-size="{ minRows: 4, maxRows: 8 }"
        />
      </div>
    </a-modal>
    <!-- 详情 -->
    <div>
      <a-drawer
        title="详情"
        :closable="false"
        :width="472"
        :visible="visible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onClose"
        :zIndex="zIndexModel"
      >
        <a-form layout="vertical" hide-required-mark>
          <a-row :style="pstyle1">
            <a-col>
              <div class="title">
                <div class="phone">
                  <span>{{ contacts }}</span> <span>{{ contactTel }}</span>
                  <div class="info-tag">
                    {{
                      aftersaleStatus == 1
                        ? "待分配"
                        : aftersaleStatus == 2
                        ? "跟进中"
                        : "完成"
                    }}
                  </div>
                </div>
                <div class="allocation_right">
                  <a-button @click="openAllot" type="primary"> 分配 </a-button>
                </div>
              </div>
              <div class="allotDialog-remarks">
                <span>备注：</span> <span>{{ remarks }}</span>
              </div>
            </a-col>
          </a-row>
          <a-row :style="pstyle1" style="margin-top: 20px;">
            <a-col>
              <div>
                <ul>
                  <li class="flex flex-a-c flex-j-s-b">
                    <div>业务类型</div>
                    <div class="m-r-20">{{ jbdOrder.serviceId_dictText }}</div>
                  </li>
                  <li class="flex flex-a-c flex-j-s-b">
                    <div>线索编号</div>
                    <div class="m-r-20">{{ jbdOrder.leadsCode }}</div>
                  </li>
                  <li class="flex flex-a-c flex-j-s-b">
                    <div>订单编号</div>
                    <div class="m-r-20">{{ jbdOrder.orderNo }}</div>
                  </li>
                  <!-- <li class="flex flex-a-c flex-j-s-b">
                    <div>跟进人</div>
                    <div class="m-r-20">工商注册</div>
                  </li> -->
                </ul>
              </div>
            </a-col>
          </a-row>
          <a-row :style="pstyle2" v-if="serviceNode.length > 0">
            <div class="timeTitle">记录</div>
            <a-timeline>
              <a-timeline-item v-for="(item, index) in serviceNode" :key="index">
                <div class="timeline-title">
                  <div class="timeline-time" v-if="item.status">{{ item.status }}</div>
                </div>
                <div class="timeline-line">
                  <div v-if="item.content">备注:{{ item.content }}</div>
                  <div class="text">
                    <a-button
                      @click="upAfterSaleFollowUp(item.status)"
                      v-if="!item.content && index == recordList.length "
                      >完成</a-button
                    >
                  </div>
                </div>
              </a-timeline-item>
            </a-timeline>
          </a-row>
        </a-form>
      </a-drawer>
      <!--  新增线索对话框 -->
      <a-modal
        title="新增线索"
        :visible="addShow"
        @ok="handleSubmit"
        @cancel="handleAddCancel"
      >
        <a-form :form="modelForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="服务内容">
            <a-cascader
              :options="typeOptions"
              v-model="modelForm.content"
              change-on-select
              :field-names="{
                label: 'name',
                value: 'id',
                children: 'childrenList',
              }"
              placeholder="请选择服务内容"
              @change="contentChange"
            />
          </a-form-item>
          <a-form-item label="联系人">
            <a-input v-model="modelForm.contacts" placeholder="请输入联系人姓名" />
          </a-form-item>
          <a-form-item label="联系电话">
            <a-input v-model="modelForm.phone" placeholder="请输入联系方式" />
          </a-form-item>
          <a-form-item label="客户类型">
            <a-select
              v-model="modelForm.leadTag"
              @change="modelChange"
              style="width: 200px"
              placeholder="请选择客户类型"
            >
              <a-select-option v-for="item in UserOptions" :key="item.value">
                {{ item.value }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="服务待办">
            <a-textarea
              placeholder="请输入服务待办事项"
              v-model="modelForm.remarks"
              :rows="4"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-row>
</template>
<script>
import {
  getDepartSelect,
  getRoleSelect,
  queryAll,
  JbdLeadsAdd,
} from "@/api/threadManage";
import {
  AfterSalelist,
  getManageById,
  AfterSaleDistribution,
  AfterSaleFollowUp,
} from "@/api/afterSale";
export default {
  name: "RoleUserList",
  data() {
    return {
      dataSource: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "30"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      zIndex: 999,
      zIndexModel: 99,
      loading: false,
      selectedRowKeys: [],
      rightcolval: 0,
      columns: [
        {
          title: "订单编号",
          align: "center",
          dataIndex: "leadsCode",
        },
        {
          title: "成单时间",
          align: "center",
          dataIndex: "createTime",
        },
        {
          title: "分配状态",
          align: "center",
          dataIndex: "aftersaleStatus",
          customRender: function (text) {
            if (text == 1) {
              return "待分配";
            } else if (text == 2) {
              return "跟进中";
            } else {
              return "完成";
            }
          },
        },
        {
          title: "售后跟进人",
          align: "center",
          dataIndex: "aftersaleUserName",
        },
        {
          title: "售后分配时间",
          dataIndex: "aftersaleDistributionTime",
          align: "center",
        },
        {
          title: "跟进节点",
          dataIndex: "followUpNode",
          align: "center",
        },
        {
          title: "最后跟进时间",
          align: "center",
          dataIndex: "followUpTime",
          // scopedSlots: { customRender: "status" },
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
      ],
      typeOptions: [], // 线索类型数据
      typeValue: [],
      statusOptions: [
        {
          value: "1",
          label: "待分配",
        },
        {
          value: "2",
          label: "跟进中",
        },
        {
          value: "3",
          label: "完成",
        },
      ], // 线索状态数据
      statusValue: [],
      threadForm: {
        code: "", // 线索编号
        time: [], // 提交时间
        submitter: "", // 提交人
        type: "", // 线索类型
        status: "", // 线索状态
      },
      // 分配弹框参数
      visibleCreateModal: false,
      objectOptions: [], //要分配的对象
      underlingOptions: [], // 要分配的下属
      // 详情
      pstyle1: {
        fontSize: "20px",
        color: "black",
        borderBottom: "1px solid #eeeeee",
        paddingBottom: "10px",
      },
      pstyle2: {
        fontSize: "17px",
        borderBottom: "1px solid #eeeeee",
        width: "100%",
        left: 0,
        lineHeight: "30px",
        padding: "20px",
      },
      visible: false,
      contacts: "", // 联系人
      contactTel: "", // 联系电话
      aftersaleStatus: "",
      jbdOrder: {},
      remarks: "", // 备注
      threadData: [
        {
          threadType: "",
          threadCode: "",
          threadSubmitter: "",
          threadSubmitterTime: "",
        },
      ],
      serviceNode: [], // 售后节点
      recordList:[],
      options: [], //  部门级联选择器
      roleList: [], // 角色下拉选择器
      ownerUserId: "", //所属用户id
      threadId: "",
      UserOptions: ["选项1", "选项2", "选项3", "蚵仔煎", "选项4", "龙须面"],
      leadTag: "",
      addShow: false,
      modelForm: {
        serviceId: "",
        phone: "",
        contacts: "",
        leadTag: "",
        remarks: "",
        content: [],
      },
      recordValue: [],
      remarkShow: false,
      saleRemarks: "",
      actionId: "",
      statusNode: "",
    };
  },
  mounted() {
    this.getList();
    this.getTypeList();
    this.getDepart();
  },
  methods: {
    Export() {
      const token = JSON.parse(window.localStorage.getItem('pro__Access-Token')).value;
      const selections = this.selectedRowKeys.toString()
      window.open(
        `https://jbd.iminggu.com/jeecg-boot/jbd/jbdOrder/exportXlsOrder?selections=${selections}&token=${token}`
      );
    },
    upAfterSaleFollowUp(statusNode) {
      this.remarkShow = true;
      this.statusNode = statusNode;
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 新增线索
    threadAdd() {
      this.addShow = true;
    },
    async handleSubmit() {
      const createBy = JSON.parse(window.localStorage.getItem("pro__Login_Userinfo"))
        .value.username;
      const params = {
        contactTel: this.modelForm.phone,
        contacts: this.modelForm.contacts,
        remarks: this.modelForm.remarks,
        serviceId: this.modelForm.serviceId,
        leadTag: this.modelForm.leadTag,
        createBy: createBy,
      };
      const res = await JbdLeadsAdd(params);
      if (res.code == 200) {
        this.$message.success("新增成功");
        this.addShow = false;
        this.getList();
      }
    },
    handleAddCancel() {
      this.addShow = false;
      this.$set(this.modelForm, "contetn", []);
      this.$set(this.modelForm, "serviceId", "");
      this.$set(this.modelForm, "phone", "");
      this.$set(this.modelForm, "contacts", "");
      this.$set(this.modelForm, "remarks", "");
      this.$set(this.modelForm, "leadTag", "");
    },
    async getList() {
      let data = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        leadsCode: this.threadForm.leadsCode,
        aftersaleUserName: this.threadForm.aftersaleUserName,
        aftersaleStatus: this.threadForm.aftersaleStatus,
      };
      const res = await AfterSalelist(data);
      this.dataSource = res.result.records;
      this.ipagination.total = res.result.total;
    },
    async getDetails(id) {
      const res = await getManageById({ id: id });
      if (res.code == 200) {
        this.jbdOrder = res.result.jbdOrder;
        this.contacts = res.result.jbdOrder.contacts; // 联系人
        this.contactTel = res.result.jbdOrder.contactTel; // 联系电话
        this.aftersaleStatus = res.result.jbdOrder.aftersaleStatus;
        this.remarks = res.result.jbdOrder.remarks; // 备注
        this.recordList = res.result.recordList
        if (res.result.recordList.length > 0) {
          const serviceNode = res.result.jbdOrder.serviceNode.map((item) => {
            return {
              status: item,
            };
          });
          serviceNode.forEach((element) => {
            res.result.recordList.forEach((core) => {
              if (element.status == core.status) {
                element.content = core.content;
              }
            });
          });
          this.serviceNode = serviceNode;
        } else {
          this.serviceNode = res.result.jbdOrder.serviceNode.map((item) => {
            return {
              status: item,
            };
          });
        }
        // this.threadData = res.result.recordList.map((item) => {
        //   return {
        //     threadType: item.types,
        //     threadCode: item.actionId,
        //     threadSubmitter: item.createBy,
        //     threadSubmitterTime: item.createTime,
        //   };
        // });
      }
    },
    modelChange(value) {
      this.modelForm.leadTag = value;
    },
    threadChange(value) {
      this.leadTag = value;
    },
    handleSelectChange() {},
    async getTypeList() {
      const res = await queryAll();
      this.typeOptions = res.result;
    },
    selectInfo() {
      this.getList();
    },
    onPickerChange(data, dateString) {
      this.threadForm.time = dateString;
    },
    resetForm() {
      // 表单重置
      this.threadForm.leadsCode = "";
      this.threadForm.timaftersaleUserNamee = "";
      this.threadForm.aftersaleStatus = "";
      this.getList();
    },
    // 分配弹框 关闭弹框事件
    openAllot() {
      if (this.recordValue.aftersaleStatus == 1) {
        this.threadId = this.recordValue.id;
        this.getDetails(this.recordValue.id);
        this.visibleCreateModal = true;
        this.getDepart();
      } else {
        this.$message.error("该线索已分配");
      }
    },
    openAllotDialog(record) {
      if (record.aftersaleStatus == 1) {
        this.threadId = record.id;
        this.getDetails(record.id);
        this.visibleCreateModal = true;
        this.getDepart();
      } else {
        this.$message.error("该线索已分配");
      }
    },
    handleModalCancel() {
      this.visibleCreateModal = false;
    },
    async handleModalOk() {
      this.visibleCreateModal = false;
      const setData = {
        id: this.threadId,
        aftersaleUser: this.ownerUserId,
      };
      const res = await AfterSaleDistribution(setData);
      if (res.code == 200) {
        this.$message.success(`${res.result}`);
        this.getList();
      }
    },
    // 详情弹框
    showDrawer(value) {
      this.visible = true;
      this.recordValue = value;
      this.actionId = value.id;
      this.getDetails(value.id);
    },
    afterVisibleChange(val) {
      console.log("visible", val);
    },
    onClose() {
      this.visible = false;
      this.serviceNode = [];
    },
    contentChange(value) {
      this.modelForm.serviceId = "";
      this.modelForm.serviceId = value[value.length - 1];
    },
    onTypeChange(value) {
      this.threadForm.type = "";
      this.threadForm.type = value[value.length - 1];
    },
    onStatusChange(value) {
      this.threadForm.aftersaleStatus = value;
    },
    handleTableChange(e) {
      this.ipagination.current = e.current;
      this.ipagination.pageSize = e.pageSize;
      this.getList();
    },
    remarkCancel() {
      this.remarkShow = false;
    },
    async handleRemark() {
      const createBy = JSON.parse(window.localStorage.getItem("pro__Login_Userinfo"))
        .value.username;
      const params = {
        content: this.saleRemarks,
        actionId: this.actionId,
        createBy,
        status: this.statusNode,
        types: "order",
      };
      const res = await AfterSaleFollowUp(params);
      if (res.code == 200) {
        this.$message.success("跟进成功");
        this.getDetails(this.recordValue.id);
        this.remarkShow = false;
      }
    },
    // 获取部门级联选择器
    async getDepart() {
      const res = await getDepartSelect();
      if (res.code == 0) {
        this.options = res.result;
      }
    },
    //线索类型
    async typeChange(e) {
      console.log(e);
      const setData = {
        id: e[1],
      };
      const res = await getRoleSelect(setData);
      if (res.code == 0) {
        this.roleList = res.result.records;
      }
    },
    // 关闭回调
    handleModalCancel() {
      this.visibleCreateModal = false;
    },
  },
};
</script>
<style lang="less" scoped>
/** Button按钮间距 */
.ant-btn {
  margin-left: 8px;
}
.allotDialog-top {
  font-size: 16px;
  border-bottom: 1px solid #eee;
  .allotDialog-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .info-left {
      width: 100%;
      height: 60px;
      background: #fafafa;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .info-tag {
        background: rgba(255, 171, 45, 0.12);
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #ffab2d;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 11px;
        margin-right: 38px;
      }
      .name {
        .tag {
          margin-left: 10px;
          font-size: 14px;
          color: rgb(255, 115, 0);
        }
      }
      .phone {
        span:nth-child(1) {
          margin: 0 20px;
        }
      }
    }
  }
  .allotDialog-remark {
    padding: 22px 26px;
    font-size: 14px;
    font-weight: 400;
    color: #656565;
    border-top: 1px solid #e8e8e8;
  }
}
.select-content {
  padding: 22px 25px;
  .select-title {
    display: flex;
    justify-content: space-between;
    div {
      flex: 1;
    }
  }
  .select-btn {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    div {
      flex: 1;
    }
  }
}
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 474px;
  height: 60px;
  background: #fafafa;
  .info-tag {
    background: rgba(255, 171, 45, 0.12);
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #ffab2d;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 5px;
    margin-left: 18px;
  }
  .allocation_right {
    margin-right: 23px;
  }
  .phone {
    display: flex;
    align-items: center;
    span:nth-child(1) {
      margin: 0 20px;
    }
  }
}
.col-title {
  display: inline-block;
  width: 120px;
  color: #000000;
  margin-right: 20px;
}
.col-text {
  font-size: 17px;
  font-family: MicrosoftYaHei;
  font-weight: 400;
  color: #bbbbbb;
}
/deep/.ant-modal-body {
  padding: 0;
}
.userTag {
  padding: 24px;
  .userTag_title {
    margin-bottom: 23px;
  }
}
/deep/.ant-drawer-body {
  padding: 0;
}
.allotDialog-remarks {
  padding: 22px 26px;
  font-size: 18px;
  font-weight: 400;
  color: #656565;
  border-top: 1px solid #e8e8e8;
}
.flex {
  display: flex;
}
.flex-a-c {
  align-items: center;
}

.flex-j-s-b {
  justify-content: space-between;
}

.ant-form {
  padding: 20px 0 0 0;
}
.info-tag {
  background: rgba(255, 171, 45, 0.12);
  border-radius: 4px;
  font-size: 14px;
  font-weight: 400;
  color: #ffab2d;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 11px;
  margin-right: 38px;
}
.m-r-20 {
  margin-right: 20px;
  color: #959595;
}
.remarksDis {
  padding: 20px !important;
}
.timeTitle{
  margin: 20px 0;
}
</style>
